import axios from "axios";
import local from "@/utils/local";
import router from "@/router";

import { ElMessage, ElLoading } from "element-plus";
import { LoadingInstance } from "element-plus/lib/components/loading/src/loading";
import type { AxiosRequestConfig, AxiosInstance, AxiosResponse } from "axios";
// 每个实例的拦截器
interface ICustomInterceptors<T = AxiosResponse> {
  InterceptorsRequest?: (config: AxiosRequestConfig) => AxiosRequestConfig;
  InterceptorsRequestError?: (err: any) => any;
  InterceptorsResponse?: (res: T) => T;
  InterceptorsResponseError?: (err: any) => any;
}

interface ICustomRequestConfig<T = AxiosResponse> extends AxiosRequestConfig {
  Interceptors?: ICustomInterceptors<T>;
}

class Request {
  instance: AxiosInstance;
  loading?: LoadingInstance;
  Interceptors?: ICustomInterceptors;
  constructor(config: ICustomRequestConfig) {
    this.instance = axios.create(config);
    // 实例拦截器
    this.Interceptors = config.Interceptors;
    this.instance.interceptors.request.use(
      this.Interceptors?.InterceptorsRequest,
      this.Interceptors?.InterceptorsRequestError
    );
    this.instance.interceptors.response.use(
      this.Interceptors?.InterceptorsResponse,
      this.Interceptors?.InterceptorsResponseError
    );
    // 所有实例拦截器
    this.instance.interceptors.request.use(
      config => {
        this.loading = ElLoading.service({
          lock: true,
          text: "数据加载中...",
          background: "rgba(0, 0, 0, 0.7)"
        });
        const user = local.get("pinia-userStore");
        // console.log(user, "user");
        if (config.headers && user && user.isLogin) {
          config.headers.authorization = `Bearer ${user?.userInfo.token}`;
        }
        return config;
      },
      error => {
        return error;
      }
    );
    this.instance.interceptors.response.use(
      res => {
        this.loading?.close();
        if (res.data.data?.msg === "无效token") {
          local.clear();
          router.push("/");
          window.location.replace("/");
          return ElMessage({
            type: "error",
            message: "登录Token失效!请重新登录~"
          });
        }

        return res.data;
      },
      error => {
        this.loading?.close();
        return error;
      }
    );
  }
  request<T>(config: ICustomRequestConfig<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      if (config.Interceptors?.InterceptorsRequest) {
        config = config.Interceptors?.InterceptorsRequest(config);
      }
      this.instance.request<any, T>(config).then(res => {
        if (config.Interceptors?.InterceptorsResponse) {
          res = config.Interceptors?.InterceptorsResponse(res);
        }
        resolve(res);
      });
    });
  }
  get<T>(config: ICustomRequestConfig<T>): Promise<T> {
    return this.request<T>({ method: "GET", ...config });
  }
  post<T>(config: ICustomRequestConfig<T>): Promise<T> {
    return this.request({ method: "POST", ...config });
  }
  put<T>(config: ICustomRequestConfig<T>): Promise<T> {
    return this.request({ method: "PUTCH", ...config });
  }
  delete<T>(config: ICustomRequestConfig<T>): Promise<T> {
    return this.request({ method: "DELETE", ...config });
  }
  patch<T>(config: ICustomRequestConfig<T>): Promise<T> {
    return this.request({ method: "PATCH", ...config });
  }
}

export default Request;
